#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
#define SRC1 "1.wav"
#define SRC2 "2.wav"
#define DST "mix.wav"

/*
	两路相同采样率 16bit PCM 归一化加权混音,data1_scale,data2_scale调节两个通道的音量, data1_scale + data2_scale <= 1
*/
void audio_mix(short *data1, short *data2, double data1_scale, double data2_scale, short *date_mix, int size)
{
	//16bit 防溢出
	int const MAX=32767;
	int const MIN=-32768;
	int same_cnt;
	for(same_cnt=0;same_cnt<size/2;same_cnt++)
	{
		*(date_mix+same_cnt) = *(data1+same_cnt)*data1_scale + *(data2+same_cnt)*data2_scale;
		*(date_mix+same_cnt) = *(date_mix+same_cnt) > MAX ? MAX : *(date_mix+same_cnt);
		*(date_mix+same_cnt) = *(date_mix+same_cnt) < MIN ? MIN : *(date_mix+same_cnt);
	}
}

int main(int argc, char const *argv[])
{
	FILE * fp1,*fp2,*fpm;
	int file_size;
	double data1_scale;
	double data2_scale;
	unsigned char wav_head[44];
	if(argc < 4 )
	{
		printf("ERR ARGs\n ./mix file_size data1_scale data2_scale\n");
		return -1;
	}
	sscanf(argv[1],"%d",&file_size);
	sscanf(argv[2],"%le",&data1_scale);
	sscanf(argv[3],"%le",&data2_scale);

	short *data1=(short *)malloc(file_size);
	short *data2=(short *)malloc(file_size);
	short *datamix=(short *)malloc(file_size);
	fp1 = fopen(SRC1,"rb");
	fp2 = fopen(SRC2,"rb");
	fpm = fopen(DST,"wb");

	/*skip fp2 wav header*/
	fseek(fp2, 44, SEEK_SET);

	/*Read and Write wav header*/
	fread(wav_head,1,44,fp1);
	fwrite(wav_head,1,44,fpm);

	/*Read pcm data from two wav files*/
	fread(data1,1,file_size,fp1);
	fread(data2,1,file_size,fp2);

	/*Do mix*/
	audio_mix(data1, data2, data1_scale, data2_scale, datamix, file_size);

	/*Write the mix wav file*/
	fwrite(datamix,1,file_size,fpm);

	/*Release and close*/
	free(data1);
	free(data2);
	free(datamix);
	fclose(fp1);
	fclose(fp2);
	fclose(fpm);
	printf("MIX Done try \t aplay mix.wav\n");
}

